<template>
  <div>
    <transition name="fade" mode="out-in">
      <div v-if="searchable" class="search-con search-con-top">
        <Select v-model="searchKey" class="search-col">
          <Option v-for="item in columns"
          v-if="item.key !== 'handle'"
          :value="item.key"
          :key="`search-col-${item.key}`"
          @click.native="setSearchTitle(item.title)"
          >{{ item.title }}</Option>
        </Select>
        <Input @on-change="handleClear"  @keyup.enter.native="handleSimpleSearch" clearable placeholder="输入关键字搜索" class="search-input" v-model="searchValue"/>
        <span @click="handleSimpleSearch" class="main-search-btn" type="primary"><Icon type="ios-search" /></span>
        <a href="javascript:void(0);" v-if="plusSearch" @click="togglePlusSearch" class="a-btn" type="primary"><Icon type="search"/>高级查询</a>
        <!-- 查询条件展示 -->
        <div v-show="simpleSearchTags.length > 0" class="simple-search-value-area">
          <Tag
          v-for='tag in simpleSearchTags'
          :key="tag.key"
          :name='tag.name'
          closable
          @on-close="handleTagClose">{{ tag.title }}:{{ tag.value }}</Tag>
          <span @click="clearSimpleSearchTags" v-if='simpleSearchTags.length > 0' class="clear-tags">清除</span>
        </div>
        <!-- 高级查询 -->
        <div style="margin: 5px auto;padding:10px; border: 1px solid #eee; border-radis: 3px;" v-if="goPlusSearch">
          <Row style="padding: auto 5px;" v-for="item in plusSearchColumnsClone"  :key="item.row">
              <Col span="8"
                style="padding: 10px 5px;"
                v-for="cell in item.list"
                :key="cell.name"
                >
                <Col span="4">
                  <div style="line-height:32px;height:32px;text-align: right; padding-right:10px;"> {{ cell.label }} :</div>
                </Col>
                <Col span="20">
                  <CommonFormCell
                  v-if="cell.type !== 'datetime'"
                  :value1='plusSearchObj[cell.name]'
                  :cellProperty="cell"
                  @on-change="handlePlusSearchCellChange"
                  ></CommonFormCell>
                  <CommonFormCell
                  v-else
                  :value1="plusSearchObj[cell.name+'_start']"
                  :value2="plusSearchObj[cell.name+'_end']"
                  :cellProperty="cell"
                  @on-change="handlePlusSearchCellChange"
                  ></CommonFormCell>
                </Col>
              </Col>
          </Row>
          <Row>
            <Col span="4" offset="1">
              <Button @click="handleSearch" class="search-btn" type="primary"><Icon type="search"/>搜索</Button>
              <Button @click="resetPlusSearch" class="search-btn" type="primary"><Icon type="search"/>重置</Button>
            </Col>
          </Row>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import CommonFormCell from './common-form-cell.vue'
import StringUtil from '@/libs/string-util'

export default {
  name: 'UnionSearch',
  components: {
    'CommonFormCell': CommonFormCell
  },
  props: {
    searchable: {
      type: Boolean,
      default () {
        return false
      }
    },
    // 简单查询的列
    // 如： [{title:用户名称, key: name}]
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    plusSearch: {
      type: Boolean,
      default () {
        return true
      }
    },
    // 高级查询的描述
    // todo 后面考虑简化语法
    plusSearchColumns: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      searchValue: '',
      searchTitle: '',
      searchKey: '',
      goPlusSearch: false,
      // 简单查询对象tag数组
      simpleSearchTags: [],
      // 高级查询对象
      simpleSearchObj: {},
      plusSearchObj: {},
      plusSearchColumnsClone: [],
      fromTagClose: false
    }
  },
  methods: {
    setDefaultSearch () {
      this.searchKey = this.columns[0].key !== 'handle' ? this.columns[0].key : (this.columns.length > 1 ? this.columns[1].key : '')
      this.searchTitle = this.columns[0].key !== 'handle' ? this.columns[0].title : (this.columns.length > 1 ? this.columns[1].title : '')
      this.doResetSearch()
    },
    handleClear (e) {
      // if (e.target.value === '') this.insideTableData = this.value
    },
    handleSearch () {
      console.log('unionSearch handleSearch:', this.plusSearchObj)
      this.$emit('on-handle-search', this.plusSearchObj)
    },
    doHandleSimpleSearch () {
      // this.searchValue = ''
      if (Object.keys(this.simpleSearchObj).length < 1) {
        console.log('查询对象为空, 停止查询。 this.simpleSearchObj:', this.simpleSearchObj)
        return -1
      }
      console.log('unionSearch handleSearch:', this.simpleSearchObj)
      this.$emit('on-handle-search', this.simpleSearchObj)
    },
    togglePlusSearch () {
      this.goPlusSearch = !this.goPlusSearch
    },
    setSearchTitle (title) {
      this.searchTitle = title
    },
    handlePlusSearchCellChange (key, value) {
      this.$set(this.plusSearchObj, key, value)
      // this.plusSearchObj[key] = value
    },
    handleTagClose (e, name) {
      // 删除该下表的tag
      for (let i = 0; i < this.simpleSearchTags.length; i++) {
        if (this.simpleSearchTags[i].name === name) {
          const item = this.simpleSearchTags[i]
          this.simpleSearchTags.splice(i, 1)
          delete this.simpleSearchObj[item.key]
        }
      }
      this.fromTagClose = true
      this.handleSimpleSearch()
      this.fromTagClose = false
    },
    clearSimpleSearchTags () {
      this.simpleSearchTags = []
      this.$emit('on-search-clear')
      this.simpleSearchObj = {}
    },
    // 做简单查询
    handleSimpleSearch () {
      // 检查是否含有该元素 , 有则直接修改
      let hasSearchKeyInSimpleSearchTags = false
      for (let i = 0; i < this.simpleSearchTags.length; i++) {
        if (this.simpleSearchTags[i].key === this.searchKey) {
          hasSearchKeyInSimpleSearchTags = true
          if (StringUtil.isNotEmpty(this.searchValue)) this.simpleSearchTags[i].value = this.searchValue
          else {
            this.simpleSearchTags.splice(i, 1)
            delete this.simpleSearchObj[this.searchKey]
          }
        }
      }
      if (!hasSearchKeyInSimpleSearchTags && StringUtil.isNotEmpty(this.searchValue) && !this.fromTagClose) {
        this.simpleSearchTags.push({
          name: this.searchKey,
          key: this.searchKey,
          title: this.searchTitle,
          value: this.searchValue
        })
      }
      this.parseSimpleSearchTagsToSimpleSearchObject()
      this.doHandleSimpleSearch()
    },
    /** 解析查询标签数组为查询对象 */
    parseSimpleSearchTagsToSimpleSearchObject () {
      if (this.simpleSearchTags.length > 0) {
        for (let i = 0; i < this.simpleSearchTags.length; i++) {
          let cell = this.simpleSearchTags[i]
          this.$set(this.simpleSearchObj, cell.key, cell.value)
        }
      }
    },
    /** 解析查询标签数组为查询对象 */
    parseSimpleSearchTagsToSearchObject () {
      if (this.simpleSearchTags.length > 0) {
        for (let i = 0; i < this.simpleSearchTags.length; i++) {
          let cell = this.simpleSearchTags[i]
          this.$set(this.plusSearchObj, cell.key, cell.value)
        }
      }
    },
    resetPlusSearch () {
      this.doResetSearch()
      this.plusSearchColumnsClone = Object.assign([], this.plusSearchColumns)
    },
    doResetSearch () {
      // 设置初始默认值
      for (let i = 0; i < this.plusSearchColumns.length; i++) {
        let item = this.plusSearchColumns[i]
        for (let j = 0; j < item.list.length; j++) {
          let cell = item.list[j]
          if (cell.type !== 'datetime') this.$set(this.plusSearchObj, cell.name, cell.default)
          else {
            this.$set(this.plusSearchObj, cell.name + '_start', cell.default)
            this.$set(this.plusSearchObj, cell.name + '_end', cell.default2)
          }
        }
      }
    }
  },
  watch: {
    columns (columns) {
      this.setDefaultSearch()
    }
  },
  mounted () {
    this.setDefaultSearch()
    this.plusSearchColumnsClone = Object.assign([], this.plusSearchColumns)
    // 设置初始默认值
    this.setDefaultSearch()
    // for (let i = 0; i < this.plusSearchColumns.length; i++) {
    //   let item = this.plusSearchColumns[i]
    //   for (let j = 0; j < item.list.length; j++) {
    //     let cell = item.list[j]
    //     this.plusSearchObj[cell.name] = cell.default
    //   }
    // }
  }
}
</script>
<style>
.simple-search-value-area {
  padding: 5px 0;
  box-sizing: border-box;
}
.clear-tags {
  cursor: pointer;
  font-size: 8px;
  text-align: center;
  color: #999;
  padding: 10px;
}
.plus-search-cell-outer {
  height: 32px;
  line-height: 32px;
}
</style>
